<template>
  <div>
    <div class="btn">
      <el-button type="warning" plain size="mini" @click="dialogVisible=true">添加</el-button>
    </div>
    <el-dialog
            title="添加商品"
            :visible.sync="dialogVisible"
            width="50%"
            :before-close="before_close_handle">
            <el-form class="form" ref="form" :rules="rule" label-position="right" label-width="60px" :model="addGood">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="addGood.title"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input-number v-model="addGood.price"  :min="1" :max="1000" ></el-input-number>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                  <el-select v-model="addGood.type" placeholder="请选择">
                    <el-option
                      v-for="item in type"
                      :key="item.id"
                      :label="item.text"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                
                <el-form-item label="描述" prop="des">
                    <el-input v-model="addGood.des"></el-input>
                </el-form-item>
                {{ fileList }}
                <el-form-item label="封面" prop="img">
                    <el-upload
                        ref="upload"
                        :file-list="fileList"
                        action="#"
                        list-type="picture-card"
                        :multiple="false"
                        :limit="1"
                        drag
                        :auto-upload="false"
                        :on-change="fileChange"
                        >
                        <i slot="default" class="el-icon-plus"></i>
                        <div slot="file" slot-scope="{file}">
                            <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                            >
                            <span class="el-upload-list__item-actions">
                                <span
                                  v-if="!disabled"
                                  class="el-upload-list__item-delete"
                                  @click="handleRemove(file)"
                                >
                                  <i class="el-icon-delete"></i>
                                </span>
                              </span>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleClose">确 定</el-button>
            </span>
        </el-dialog>
    <el-table
        stripe
        border
        :data="lists"
        style="width: 100%">
        <el-table-column
          label="id"
          prop="id">
        </el-table-column>
        <el-table-column
          label="标题"
          prop="title">
        </el-table-column>
        <el-table-column
          label="描述"
          prop="des">
        </el-table-column>
        <el-table-column
          label="价格"
          prop="price">
        </el-table-column>
        <el-table-column
          label="图片"
          >
          <template slot-scope="scope">
              <el-image :src="scope.row.img"></el-image>
          </template>
        </el-table-column>
        <el-table-column
          align="right">
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="pageMap.key"
              size="mini"
              placeholder="输入关键字搜索" @keyup.enter.native="search_handler"/>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"  >删除</el-button>
          </template>
        </el-table-column>
    </el-table>
      <div class="page">
        <el-pagination
        layout="prev, pager, next"
        :total="total"
        @prev-click="current_change"
        @next-click="current_change"
        @current-change="current_change">
      </el-pagination>
      </div>
  </div>
</template>
<script>
import { category_list } from '@/api/category_api'
import { del_good, list,good_add } from '@/api/goods_api'

export default{
  data(){
    return{
      type:[],
      disabled: false,
      lists:[],
      pageMap:{
        now_page:1,
        limit:10,
        key:""
      },
      total:0,
      fileList:[],
      dialogVisible: false,
      addGood:{
        img:"",
        title:"",
        price:1,
        des:"",
        type:""
      },
      rule:{
          title:[
            {required:true,message:'请输入商品标题',trigger:'blur'}
          ],
          price:[
            {required:true,message:'请输入商品价格',trigger:'blur'},
          ],
          des:[
            {required:true,message:'请输入商品描述',trigger:'blur'},
          ],
          img:[
            {required:true,message:'请上传商品照片',trigger:'blur'},
          ],
          type:[
            {required:true,message:'请选择类型',trigger:'blur'},
          ]
      },
    }
  },
  methods:{
    current_change(page){
      this.pageMap.now_page = page
      this.good_info()
    },
    search_handler(){
      this.pageMap.now_page = 1
      this.good_info()
    },
    async category_list(){
      const {data:res} = await category_list()
      this.type = res.data

    },
    handleDelete(index,row){
       this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await del_good(row.id)
          this.$message({
            type: res.code==200?'success':'error',
            message: res.message
          });
          if(res.code==200)this.good_info()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    async handleClose(){
      this.$refs['form'].validate(async (valid)=>{
        if(valid){
          const res = await good_add(this.addGood)
          this.$message({
            type:res.data.code==200?'success':'error',
            message:res.data.msg
          })
          this.dialogVisible = false
          this.good_info()
          this.addGood = {
            img:"",
            title:"",
            price:1,
            des:""
          }
        }else{
          return false;
        }
      })
    },
    blob2Base64(blob) {
      return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.addEventListener('load', () => {
              const base64 = reader.result?.toString() || '';
              resolve(base64);
          });
          reader.addEventListener('error', () => {
              reject(new Error('message'));
          });
          reader.readAsDataURL(blob);
      });
  },
  async good_info(){
    const {data:res} = await list(this.pageMap)
    this.pageMap.key = ""
    this.lists = res.data.list.map(k=>{
      return {
        id:k.id,
        title:k.title,
        des:k.des,
        price:k.price,
        img:this.revert(k.img)
      }
    })
    this.total = res.data.total
  },
  revert(data){
      var parts = data.split(';base64,'),
      contentType = parts[0].split(':')[1],
      raw = window.atob(parts[1]),
      length = raw.length,
      arr = new Uint8Array(length);
      for (var i = 0; i < length; i++) {
          arr[i] = raw.charCodeAt(i);
      }
      var blob = new Blob([arr], { type: contentType });
      return URL.createObjectURL(blob);
    },
    before_close_handle(){
      this.addGood={
        img:"",
        title:"",
        price:1,
        des:""
      }
        this.dialogVisible = false
    },
    async fileChange(file){
      console.log(file);
      let array = ['image/png','image/jpeg']
      if(array.some(v=>v==file.raw.type)){
        const blob = new Blob([file.raw],{type:file.raw.type})
        const base = await this.blob2Base64(blob)
        this.addGood.img = base
      }else{
        this.handleRemove()
        this.$message({
          type:'warning',
          message:'仅支持png、jpeg！！！'
        })
      }
     
    },
    handleRemove(file){
      this.$refs.upload.clearFiles()
      this.addGood.img = ""
    },
  },
  created(){
    this.good_info()
    this.category_list()
  }
}
</script>
<style lang="scss" scoped>
.el-upload-dragger{
  width: auto;
  height: auto;
}
.page{
  float: right;
  margin-top: 2%;
}
.btn{
  margin-bottom: 2%;
}
</style>